#include "socket_server.h"

uint32_t main(void) {

	struct sockaddr_in my_addr;
	uint32_t hsock;
	uint32_t *p_int;

	socklen_t addr_size = 0;
	uint32_t *csock;
	struct sockaddr_in sadr;
	pthread_t thread_id = 0;

	hsock = socket(AF_INET, SOCK_STREAM, 0);
	if (hsock == -1){
		printf("Error en el socket() \n");
	}

	p_int = (uint32_t*)malloc(sizeof(uint32_t));
	*p_int = 1;

	if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(uint32_t)) == -1 ) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ) {
		printf("Error en el setsockopt() \n");
	}
	free(p_int);

	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(PUERTO);

	memset(&(my_addr.sin_zero), 0, 8);
	my_addr.sin_addr.s_addr = INADDR_ANY;

	if (bind(hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1) {
		printf("Error en el bind() \n");
	}

	if(listen(hsock, MAX_CONEXIONES) == -1) {
		printf("Error en el listen() \n");
	}

	addr_size = sizeof(struct sockaddr_in);

	while(1) {
		printf("Esperando conexión...\n");
		csock = (uint32_t*)malloc(sizeof(uint32_t));
		if((*csock = accept( hsock, (struct sockaddr*)&sadr, &addr_size))!= -1){
			printf("\n Conexión recibida desde %s \n", inet_ntoa(sadr.sin_addr));
			pthread_create(&thread_id, NULL, (void*)&socketHandler, (void*)csock);
			pthread_detach(thread_id);
		} else {
			printf("Error en el accept()\n");
		}
	}

	return 0;
}
